package com.youjiang.meeting.utils.weixin;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.dom4j.DocumentException;

import com.google.gson.Gson;

/**
 * <p>
 * Title: WeixinController
 * </p>
 * <p>
 * Description:微信对接
 * </p>
 * <p>
 * Company: YouJiang
 * </p>
 *
 * @author feng
 * @date 2016年11月14日 下午6:30:46
 * @version 1.0
 */
public class WeixinController {
	/***
	 * 初始化微信参数
	 */
	public WeixinController() {
		
	    
	}
	
	public void model(HttpServletRequest request, HttpServletResponse response) throws IOException, DocumentException {
		String modth = request.getMethod();
		if (modth.equalsIgnoreCase("get")) {
			doGet(request, response);
		} else {
			doPost(request, response);
		}
	}

	// get方法的检验
	private String doGet(HttpServletRequest req, HttpServletResponse resp) {
		String signature = req.getParameter("signature");
		String timestamp = req.getParameter("timestamp");
		String nonce = req.getParameter("nonce");
		String echostr = req.getParameter("echostr");

		if (CheckUtil.checkSignature(signature, timestamp, nonce)) {
			return echostr;
		}
		return null;
	}

	// post消息的接收与回复
	private String doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, DocumentException {
		Map<String, String> map = MessageUtil.XMLToMessage(req);
		// 去到那个微信号
		String toUserName = map.get("ToUserName");
		// 从那个微信号发过来的
		String fromUserName = map.get("FromUserName");
		// 时间
		String createTime = map.get("CreateTime");
		// 消息类型
		String msgType = map.get("MsgType");
		// 消息内容
		String content = map.get("Content");
		// 消息的id
		String msgId = map.get("MsgId");
		// 事件类型
		String event = map.get("Event");
		return null;
	}

	public String sign(String nowurl,HttpServletRequest req,String appid,String appsecrect) throws Exception {
		if (StringUtils.isEmpty(WeixinUtil.SYSTEMPATH)) {
			WeixinUtil.SYSTEMPATH=req.getServletContext().getRealPath("/weixinfile/");
		}
		Map<String, String> info = Sign.sign(nowurl,appid,appsecrect);
		Gson gson = new Gson();
		return gson.toJson(info);
	}
}
